package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 检查用户是否登入成功
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器 支持通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1. 获取本次请求的 URI
        String requestURL = request.getRequestURI();
        // 定义不需要请求的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/front/page/login",
                "/user/yanzhengma",
                "/user/login"
        };
        log.info("拦截路径：{}",requestURL);
        //2. 判断本次请求是否需要请求
        boolean check = check(requestURL, urls);
        //3. 如果不需要处理 则直接放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //4-1. 判断登入状态,如果已登入 则直接放行
        if (request.getSession().getAttribute("employee") != null){
            //将登入用户 id 存入 ThreadLocal 线程中
            BaseContext.setUserId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }
        //4-2. 判断登入状态,如果已登入 则直接放行
        if (request.getSession().getAttribute("user") != null){
            //将登入用户 id 存入 ThreadLocal 线程中
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }
        //5.如果未登入则返回登入结果 通过输出流方式向客户页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    /**
     * 路径匹配 检查本次请求是否需要放行
     * @param requestURI
     * @return
     */

    public boolean check(String requestURI,String[] urls){
        for (String url : urls) {
                boolean match = PATH_MATCHER.match(url,requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
